package com.open.party.cloud.view.mine

import android.os.Bundle
import android.view.View
import cn.android.x.model.AppVersionEntity
import cn.android.x.model.data.ResultInfo
import cn.android.x.parent.AppEventBusTitleBaseActivity
import cn.android.x.parent.AppTitleBaseActivity
import com.gyf.immersionbar.ImmersionBar
import com.king.app.dialog.AppDialog
import com.king.app.dialog.AppDialogConfig
import com.king.app.updater.AppUpdater
import com.open.party.cloud.R
import com.open.party.cloud.viewModel.BaseViewModel
import com.sinothk.android.utils.XUtils
import kotlinx.android.synthetic.main.mine_app_share_activity.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class AppDownloadMainActivity : AppEventBusTitleBaseActivity() {
    private var baseViewModel: BaseViewModel? = null

    override fun getLayoutResId(): Int = R.layout.mine_app_share_activity

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setViewTitle("应用下载")
        ImmersionBar.with(this@AppDownloadMainActivity)
            .statusBarDarkFont(false).init()
        baseViewModel = BaseViewModel()

        showLoadingDialog("正在检测")
        baseViewModel!!.getAppInfoForLastVersion("appInfoForLastVersion")
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun receiveAppVersionEventBus(resultInfo: ResultInfo<AppVersionEntity?>) {

        if ("appInfoForLastVersion" != resultInfo.eventType) {
            return
        }

        hideLoadingDialog()

        if (resultInfo.code == ResultInfo.SUCCESS) {
            val appVersion = resultInfo.data
            if (appVersion != null) {
                if (appVersion.verNumber > XUtils.app().appVersionCode) { //简单弹框升级
                    val config = AppDialogConfig()
                    config.setTitle("新版本升级")
                        .setOk("升级")
                        .setContent(
                            XUtils.string().getNotNullValue(appVersion.updateContent)
                        ).onClickOk = View.OnClickListener { v: View? ->
                        if (XUtils.string().isNotEmpty(appVersion.filePath)) {
                            AppUpdater.Builder()
                                .serUrl(appVersion.filePath)
                                .build(this@AppDownloadMainActivity)
                                .start()
                        } else {
                            XUtils.toast().show("地址不可用")
                        }
                        AppDialog.INSTANCE.dismissDialog()
                    }
                    AppDialog.INSTANCE.showDialog(this@AppDownloadMainActivity, config)
                } else {
                    XUtils.toast().show("当前已是最新版本")
                }
            }
        } else if (resultInfo.code == ResultInfo.TOKEN_OVERDUE) {
        } else {
            XUtils.toast().show(resultInfo.msg)
        }
    }
}